package com.lin.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lin.service.UserService;
import com.lin.serviceimpl.UserServiceImpl;

/**
 * ��������û���������Ŀ��Ʋ�
 */
//@WebServlet("/AddUsernameServlet")
public class AddUsernameServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		/* 允许跨域的主机地址 */
		response.setHeader("Access-Control-Allow-Origin", "*");  
		/* 允许跨域的请求方法GET, POST, HEAD 等 */
		response.setHeader("Access-Control-Allow-Methods", "*");  
		/* 重新预检验跨域的缓存时间 (s) */
		response.setHeader("Access-Control-Max-Age", "3600");  
		/* 允许跨域的请求头 */
		response.setHeader("Access-Control-Allow-Headers", "*");  
		/* 是否携带cookie */
		response.setHeader("Access-Control-Allow-Credentials", "true"); 
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username+password);
		UserService service = new  UserServiceImpl();
		
		int insertUser;
		int userCount;
		try {
			 userCount = service.checkUsernameCount(username);
			 if(userCount>0) {
				 response.getWriter().write("same");
			 }else {
				 insertUser = service.insertUser(username, password);
				 System.out.println("成功新建用户"+insertUser);
				 if(insertUser>0) {
					 response.getWriter().write("success");
				 }else {
					 response.getWriter().write("fail");
				 }
			 }
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		doGet(request, response);
}
}
